//
//  RFUMPSDK.swift
//  RFAds
//
//  Created by Roffa Zhou on 2023/2/15.
//  如果您决定在应用中添加应用跟踪透明度 (ATT)，则可以使用 User Messaging Platform (UMP) SDK 来触发 IDFA 铺垫消息，让用户了解您为何需要此权限。请注意，使用 UMP SDK 会影响您应用的所有用户。
//https://developers.google.com/admob/ios/privacy?hl=zh-cn#app_tracking_transparency

import Foundation
import UserMessagingPlatform


/// The Google Mobile Ads SDK provides the User Messaging Platform (Google's
/// IAB Certified consent management platform) as one solution to capture
/// consent for users in GDPR impacted countries. This is an example and
/// you can choose another consent management platform to capture consent.

public class RFUMPSDK: NSObject {
    static public let shared = RFUMPSDK()
    public var isRequestSucc = false  //生命周期内只要成功调用就会置为true
    public var isCallUpdating = false  //当前是否在调用gatherConsent方法

    public var canRequestAds: Bool {
        return ConsentInformation.shared.canRequestAds
    }

    public var isPrivacyOptionsRequired: Bool {
        return ConsentInformation.shared.privacyOptionsRequirementStatus == .required
    }
    //是否已经弹出过同意框
    public var isShowedConsentAlert: Bool {
        return ConsentInformation.shared.consentStatus == .obtained
    }
    public func loadAndPresentIfRequired(_ vc: UIViewController, consentGatheringComplete: @escaping (Error?) -> Void ){
        ConsentForm.loadAndPresentIfRequired(from: vc) {[weak self]
            loadAndPresentError in
            if loadAndPresentError == nil {
                self?.isRequestSucc = true
            }
            
            // Consent has been gathered.
            consentGatheringComplete(loadAndPresentError)
        }
    }
    /// Helper method to call the UMP SDK methods to request consent information and load/present a
    /// consent form if necessary.
    /// updateComplete: update调用成功，如from != nil ,则会调用
    public func gatherConsent(
        from consentFormPresentationviewController: UIViewController? = nil, isDebug: Bool = false, updateComplete: (() -> Void)? = nil,
        consentGatheringComplete: @escaping (Error?) -> Void
    ) {
        let parameters = RequestParameters()
        
        if isDebug {
            //For testing purposes, you can force a UMPDebugGeography of EEA or not EEA.
            let debugSettings = DebugSettings()
            debugSettings.geography = DebugGeography.EEA
            parameters.debugSettings = debugSettings
        }
        isCallUpdating = true

        // Requesting an update to consent information should be called on every app launch.
        ConsentInformation.shared.requestConsentInfoUpdate(with: parameters) {[weak self]
            requestConsentError in
            guard requestConsentError == nil else {
                self?.isRequestSucc = false
                self?.isCallUpdating = false
                return consentGatheringComplete(requestConsentError)
            }
            if isDebug {
                print("UMP开始\(String(describing: self?.isRequestSucc))进行loadAndPresentIfRequired：\(String(describing: consentFormPresentationviewController))")
            }
            if let consentFormPresentationviewController {
                if let cb = updateComplete {
                    cb()
                }
                ConsentForm.loadAndPresentIfRequired(from: consentFormPresentationviewController) {
                    loadAndPresentError in
                    if loadAndPresentError == nil {
                        self?.isRequestSucc = true
                    }
                    if isDebug {
                        print("UMP loadAndPresentIfRequired callback：\(String(describing: loadAndPresentError))")
                    }
                    self?.isCallUpdating = false

                    // Consent has been gathered.
                    consentGatheringComplete(loadAndPresentError)
                }
            } else {
                consentGatheringComplete(nil)
                self?.isRequestSucc = true
                self?.isCallUpdating = false

            }
        }
    }
    
    /// Helper method to call the UMP SDK method to present the privacy options form.
    public func presentPrivacyOptionsForm(
        from viewController: UIViewController, completionHandler: @escaping (Error?) -> Void
    ) {
        ConsentForm.presentPrivacyOptionsForm(
            from: viewController, completionHandler: completionHandler)
    }
    
    public func reset() {
        ConsentInformation.shared.reset()
    }
    
    //查看具体key:https://github.com/InteractiveAdvertisingBureau/GDPR-Transparency-and-Consent-Framework/blob/master/TCFv2/IAB%20Tech%20Lab%20-%20CMP%20API%20v2.md
    //用户是否已点击了consent或accept all
//    let a1 = MGCacheEnum.get(.userdefault, "IABTCF_CmpSdkVersion").result()
//    let a2 = MGCacheEnum.get(.userdefault, "IABTCF_PurposeOneTreatment").result()
//    let a3 = MGCacheEnum.get(.userdefault, "IABTCF_TCString").result()
//    let a4 = MGCacheEnum.get(.userdefault, "IABTCF_VendorConsents").result()
//    if let a5 = MGCacheEnum.get(.userdefault, "IABTCF_PurposeConsents").result() as? String {
//        if a5.count > 0, a5.hasPrefix("11") {  //已经点击consent
//            mg_logTrace("用户已经点击广告consent或accept all")
//        } else if a5.hasPrefix("0") { //用户点击了 manage option，并且点击了 confirm choices
//            mg_logTrace("用户已经点击广告manage option的confirm choices")
//        }
//    }
    //未弹框时返回nil, 已弹框并且用户已经点击广告consent或accept all返回true
    public func userHasConsent() -> Bool? {
        if let str = UserDefaults.standard.object(forKey: "IABTCF_PurposeConsents") as? String {
            if str.count > 0, str.hasPrefix("11") {  //已经点击consent
                return true
            }
        } else {
            return nil
        }
        
        return false
    }
    
}


/*
public class RFUMPSDK {
    public func installUMP(_ vc: UIViewController , callback: ((NSError?)->Void)? = nil){
        let parameters = UMPRequestParameters()
        parameters.tagForUnderAgeOfConsent = false
        
        UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: parameters) { error  in
            if let err = error as? NSError {
                callback?(err)
            }else{
                callback?(nil)

                let formStatus = UMPConsentInformation.sharedInstance.formStatus
                if formStatus == UMPFormStatus.available {
                    self.loadForm(vc)
                }
            }
        }
    }
}
extension RFUMPSDK {
    private func loadForm(_ vc: UIViewController) {
        // Loads a consent form. Must be called on the main thread.
        UMPConsentForm.load { form , error in
            
            if let err = error as? NSError {

            }else{
                if UMPConsentInformation.sharedInstance.consentStatus == UMPConsentStatus.required {
                    form?.present(from: vc, completionHandler: { dismissError in
                        if UMPConsentInformation.sharedInstance.consentStatus == UMPConsentStatus.obtained{
                            // App can start requesting ads.

                        }
                    })
                }
            }
        }
    }
}
*/
